package tk.pptiger.controller;

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;

@WebServlet(name = "UploadServlet", urlPatterns = {"/upload.do"})
public class FileUploadBodyView extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String contentType = req.getContentType();
        int formDataLength = req.getContentLength();

        DataInputStream dataStream = new DataInputStream(req.getInputStream());
        byte datas[] = new byte[formDataLength];
        int totalBytes = 0;
        while (totalBytes < formDataLength) {
            int bytes = dataStream.read(datas, totalBytes, formDataLength);
            totalBytes += bytes;
        }

        // 取得所有本體內容的字串表示
        String reqBody = new String(datas, "ISO-8859-1");
        // 取得上傳的檔案名稱
        String filename = reqBody.substring(
                reqBody.indexOf("filename=\"") + 10);
        filename = filename.substring(0, filename.indexOf("\n"));
        filename = filename.substring(
                filename.lastIndexOf("\\") + 1, filename.indexOf("\""));

        // 取得檔案區段邊界資訊
        String boundary = contentType.substring(
                contentType.lastIndexOf("=") + 1, contentType.length());

        // 取得實際上傳檔案的起始與結束位置
        int pos;
        pos = reqBody.indexOf("filename=\"");
        pos = reqBody.indexOf("\n", pos) + 1;
        pos = reqBody.indexOf("\n", pos) + 1;
        pos = reqBody.indexOf("\n", pos) + 1;
        int boundaryLoc = reqBody.indexOf(boundary, pos) - 4;
        int startPos = ((reqBody.substring(0, pos))
                .getBytes("ISO-8859-1")).length;
        int endPos = ((reqBody.substring(0, boundaryLoc))
                .getBytes("ISO-8859-1")).length;

        // 輸出至檔案
        // FileOutputStream fileOutputStream =
        //         new FileOutputStream("c:/workspace/" + filename);
        // fileOutputStream.write(datas, startPos, (endPos - startPos));
        // fileOutputStream.flush();
        // fileOutputStream.close();
    }
}
